"""
--------------------------------------------------------------------------------
功能:上位机和下位机通信的串口协议
日期:2025-06-07
作者:Unirobot
QQ交流群:811348489
寄语：代码中能遇见你，真好，有你，真好.
署名：有你同创智能机器人科技(北京)有限公司
--------------------------------------------------------------------------------
"""

#!/usr/bin/env python3

import sys
import signal
import time
import serial
import serial.tools.list_ports


class SerialPort:
    def __init__(self, port="/dev/ttyS1", baudrate=115200, timeout=1):
        """初始化串口
        
        Args:
            port (str): 串口设备路径，默认 /dev/ttyS1
            baudrate (int): 波特率，默认 115200
            timeout (int): 超时时间（秒），默认 1
        """
        self.port = port
        self.baudrate = baudrate
        self.timeout = timeout
        self.ser = None

    def open(self):
        """打开串口"""
        try:
            self.ser = serial.Serial(
                self.port, 
                self.baudrate, 
                timeout=self.timeout
            )
            # print(f"Serial opened: {self.ser}")
            # print("\033[42m串口打开成功\033[0m")      # 串口打开成功
            return True
        except Exception as e:
            # print(f"Failed to open serial: {e}")
            print("\033[41m串口打开失败\033[0m")      # 红色背景
            return False

    def close(self):
        """关闭串口"""
        if self.ser and self.ser.is_open:
            self.ser.close()
            print("Serial closed.")

    # def serial_send(self, data):
    #     """发送数据到串口
        
    #     Args:
    #         data (str): 要发送的字符串数据（如 "AA55"）
        
    #     Returns:
    #         int: 实际发送的字节数，失败返回 -1
    #     """
    #     if not self.ser or not self.ser.is_open:
    #         print("Serial port is not open!")
    #         return -1
    #     print("data:", data)

    #     try:
    #         write_num = self.ser.write(data.encode('UTF-8'))
    #         # write_num = self.ser.write(data)
    #         print(f"Send: {data} (Bytes: {write_num})")
    #         return write_num
    #     except Exception as e:
    #         print(f"Error in serial_send: {e}")
    #         return -1
    def serial_send(self, data):
        """发送二进制数据到串口
        
        Args:
            data (bytes): 要发送的二进制数据（如 b'\xAA\xBB\x03'）
        
        Returns:
            int: 实际发送的字节数，失败返回 -1
        """
        if not self.ser or not self.ser.is_open:
            print("Serial port is not open!")
            return -1

        try:
            # 直接发送 bytes 数据（无需 encode）
            write_num = self.ser.write(data)
            # print(f"Send: {data.hex(' ').upper()} (Bytes: {write_num})")
            return write_num
        except Exception as e:
            print(f"Error in serial_send: {e}")
            return -1

    def serial_recv(self, expected_bytes=None):
        """从串口接收数据
        
        Args:
            expected_bytes (int): 期望接收的字节数（None 表示读取全部缓存）
        
        Returns:
            str: 接收到的数据（解码后的字符串），失败返回 None
        """
        if not self.ser or not self.ser.is_open:
            print("Serial port is not open!")
            return None

        try:
            if expected_bytes is None:
                received_data = self.ser.read_all().decode('UTF-8')
            else:
                received_data = self.ser.read(expected_bytes).decode('UTF-8')
            
            print(f"Recv: {received_data}")
            return received_data
        except Exception as e:
            print(f"Error in serial_recv: {e}")
            return None



# if __name__ == '__main__':
#     signal.signal(signal.SIGINT, signal_handler)
    
#     # 创建串口实例
#     serial_port = SerialPort(port="/dev/ttyS1", baudrate=115200)
    
#     if not serial_port.open():
#         print("Serial test failed!")
#         sys.exit(1)
    
#     print("Starting demo now! Press CTRL+C to exit")
    
#     try:
#         while True:
#             # 发送数据
#             send_data = "AA55"
#             bytes_sent = serial_port.serial_send(send_data)
            
#             # 接收数据（假设回显字节数=发送字节数）
#             if bytes_sent > 0:
#                 serial_port.serial_recv(bytes_sent)
            
#             time.sleep(1)
#     except KeyboardInterrupt:
#         print("\nExiting...")
#     finally:
#         serial_port.close()
#         print("Serial test completed.")